/**
 * Created by tongchia on 14/11/6.
 */

(function(fn){
    if (!fn.map) fn.map=function(f){var r=[];for(var i=0;i<this.length;i++)r.push(f(this[i]));return r}
    if (!fn.filter) fn.filter=function(f){var r=[];for(var i=0;i<this.length;i++)if(f(this[i]))r.push(this[i]);return r}
})(Array.prototype);

/**
 * options
 */
var priceItems=[{name:'3万及以下',value:'3'}, {name:'3-5万',value:'35'}, {name:'5-8万',value:'58'}, {name:'8-10万',value:'810'}, {name:'10-15万',value:'1015'}, {name:'15-20万',value:'1520'}, {name:'20-30万',value:'2030'}, {name:'30-50万',value:'3050'}, {name:'50万以上',value:'50'}]
  , levelItems=[{name:'微型车', value:'wx'}, {name:'小型车', value:'xx'}, {name:'紧凑型', value:'jc'}, {name:'中型车', value:'zx'}, {name:'中大型', value:'zd'}, {name:'豪华车', value:'hh'}, {name:'MPV', value:'mpv'}, {name:'SUV', value:'suv'}, {name:'跑车', value:'pc'}, {name:'微面', value:'wm'}, {name:'皮卡', value:'pk'}]
  , ageItems=[{name:'1年内', value:'1'}, {name:'2年内', value:'2'}, {name:'3年内', value:'3'}, {name:'5年内', value:'5'}, {name:'8年内', value:'8'}, {name:'10年内', value:'10'} ]
  , mileageItems=[{name:'1万公里', value:'1'}, {name:'3万公里', value:'3'}, {name:'5万公里', value:'5'}, {name:'10万公里', value:'10'}];

var treeURL='../dd/getTreeMenu?id='
	  , carsURL='./carsearch?'
	  , searchURL='../car/suggest?q='
	  , imgURL='../attached/image/'
	  , carURL='./:id/carDetail.shtml'
	  , method='get';

window.carsData=[];
window.selected={brands:'',series:'',models:'',brandsText:'',seriesText:'',modelsText:'',price:'',level:'',age:'',mileage:'',condition:'',pagination:''};
var brands=jQuery('#brands')
  , series=jQuery('#series')
  , models=jQuery('#models')
  , resetBtn=jQuery('#reset')
  , cars=jQuery('#cars')
  , price=jQuery('#price')
  , level=jQuery('#level')
  , age=jQuery('#age')
  , mileage=jQuery('#mileage')
  , condition=jQuery('#condition')
  , pagination=jQuery('#pagination');

var queryObj={
  brandsText:'sbrands',
  seriesText:'scarseries',
  modelsText:'scarstardard',
  price:'sprice',
  age:'scaryear',
  level:'ccarlevel',
  mileage:'mileage',
  condition:'condition',
  pagination:'currentPage'
};


/**
 * 分页
 */
function flip (n){ //翻页
  return function(){
    window.selected.pagination=n;
    cars.update();
  }
}
pagination.update=function(total, current){
  var $e=jQuery(this);
  $e.empty();
  if(current>1){
    jQuery('<span />').html('<a href="javascript:void(0);">上一页</a>').click(flip(current-1)).appendTo($e);
  }else{
    jQuery('<span class="disable"/>').html('<a href="javascript:void(0);">上一页</a>').appendTo($e);
  }
  if(current>4){
    jQuery('<span />').html('<a href="javascript:void(0);">1</a>').click(flip(1)).appendTo($e);
    jQuery('<span class="disable"/>').html('<a href="javascript:void(0);">......</a>').appendTo($e);
  }
  if(current==4){
    jQuery('<span />').html('<a href="javascript:void(0);">1</a>').click(flip(1)).appendTo($e);
  }
  for(var i=((current-2)>0?current-2:1); i<=((current+2)<total?current+2:total); i++){
    if(i==current){
      jQuery('<span class="disable"/>').html('<a class="current" href="javascript:void(0);">'+i+'</a>').appendTo($e);
    }else{
      jQuery('<span />').html('<a href="javascript:void(0);">'+i+'</a>').click(flip(i)).appendTo($e);
    }
  }
  if(total-current==3){
    jQuery('<span />').html('<a href="javascript:void(0);">'+total+'</a>').click(flip(1)).appendTo($e);
  }
  if(total-current>3){
    jQuery('<span class="disable"/>').html('<a href="javascript:void(0);">......</a>').appendTo($e);
    jQuery('<span />').html('<a href="javascript:void(0);">'+total+'</a>').click(flip(total)).appendTo($e);
  }
  if(current<total){
    jQuery('<span />').html('<a href="javascript:void(0);">下一页</a>').click(flip(current+1)).appendTo($e);
  }else{
    jQuery('<span class="disable"/>').html('<a href="javascript:void(0);">下一页</a>').appendTo($e);
  }
};

/**
 * 刷新汽车列表
 */
function createCars(data){
  for(var i=0;i<data.length;i++){
    var d=data[i],href=carURL.replace(':id', d.id),html=' \
              <div class="hm_leftg"></div>\
              <div style="float:left;"><a href="'+ href +'"><img class="lazy" data-original="'+ imgURL+d.imageName +'" src="../style/loading.gif"  width="241" height="180"></a></div>\
              <div class="hm_lefth">\
                <h2><a href="'+href+'">'+ d.title +'</a></h2>\
                <h2>￥<i style="font-size:24px; color:#ff0000;">'+ d.sprice +'</i>万</h2>\
                <div class="hm_lefti">\
                  <h3>'+ d.mileage +' 公里</h3>\
                  <h3>'+ d.licensyear +' 上牌</h3>\
                  <div class="clear"></div>\
                </div>\
                <div class="clear"></div>\
                <h4><a href="'+href+'">'+ d.sjmc +'</a></h4>\
                <div class="clear"></div>\
              </div>\
              <div class="clear"></div>';
    $('<div class="hm_leftf"/>').html(html).appendTo(cars);
  }
}
function query2Str(){
  var querys={};
  jQuery.each(window.selected, function(k, v){
    if(v&&queryObj[k]){querys[queryObj[k]]=v}
  });
  return jQuery.param(querys)
}
cars.update= function(){
  var self=$(this);
  jQuery[method](carsURL+query2Str(),function(data){
    data=jQuery.parseJSON(data);
    self.empty();
    if(data.list.length>0){
      createCars(data.list);
      pagination.update(data.totalPage, data.currentPage)
    }else{
      jQuery('<h1 style="text-align:center;color:grey;margin-top:60px"/>').html('抱歉! 没有您要找的车型!').appendTo(self);
    }
  });
};
cars.updateByKey= function(){
  var self=$(this),q=jQuery.getQueryParameters().key.replace(/\+/g,'%20'),str=decodeURI(q);
  jQuery('#searchInput').val(str);
  jQuery[method](searchURL+q,function(data){
    data=jQuery.parseJSON(data);
    self.empty();
    if(data.list.length>0){
      createCars(data.list);
      pagination.update(data.totalPage, data.currentPage)
    }else{
      jQuery('<h1 style="text-align:center;color:grey;margin-top:60px"/>').html('抱歉! 没有您要找的车型!').appendTo(self);
    }
  });
};


/**
 * 车型选单
 *
 */
var updateSelect=function(id, fn){
  var $e = $(this),
    createOptions=function(data){
      if(data.length>0){
        for(var i=0;i<data.length;i++){
          if(data[i].isTitle==='是'){
            jQuery('<option class="tc-slt-dt"/>').attr('disabled',"disabled").html(data[i].text).appendTo($e);
          }else{
            jQuery('<option class="tc-slt-dd"/>').attr('value',data[i].id).html(data[i].text).appendTo($e);
          }
        }
      }
    };
  $e.empty();
  if(window.carsData[id]){
    createOptions(window.carsData[id]);
  }else{
    jQuery[method](treeURL+id,function(data){
      window.carsData[id]=jQuery.parseJSON(data);
      createOptions(window.carsData[id]);
    });
  }
  $e.change(function(){
    fn($e.children('option:selected').val(), $e.children('option:selected').html());
  });
};
function emtpySelect(name){
  return function(){
    var $e = $(this),nameText=name+'Text';
    window.selected[name]='';
    window.selected[nameText]='';
    $e.empty();
  }
}
brands.update=updateSelect;
series.update=updateSelect;
models.update=updateSelect;
brands.clean=emtpySelect('brands');
series.clean=emtpySelect('series');
models.clean=emtpySelect('models');
function resetSelect(){
  window.selected.brands='';
  window.selected.brandsText='';
  series.clean();
  models.clean();
  $('<option class="tc-slt-null"/>').attr('value','all').html('请选择车系').prependTo(series);
  $('<option class="tc-slt-null"/>').attr('value','all').html('请选择车型').prependTo(models);
  cars.update();
  resetBtn.addClass('current')
}
function selectModel(id, text){
  if(id=='all'){
    window.selected.models='';
    window.selected.modelsText='';
  }else{
    window.selected.models=id;
    window.selected.modelsText=text;
  }
  cars.update()
}
function selectSeries(id, text){
  if(id=='all'){
    window.selected.series='';
    window.selected.seriesText='';
    models.clean();
  }else{
    window.selected.series=id;
    window.selected.seriesText=text;
    models.clean();
    models.update(id, selectModel);
  }
  $('<option class="tc-slt-null"/>').attr('value','all').html('请选择车型').prependTo(models);
  cars.update()
}
function selectBrand(id, text){
  if(id=='all'){
    resetSelect();
  }else{
    window.selected.brands=id;
    window.selected.brandsText=text;
    series.update(id, selectSeries);
    models.clean();
    resetBtn.removeClass('current')
  }
  $('<option class="tc-slt-null"/>').attr('value','all').html('请选择车系').prependTo(series);
  $('<option class="tc-slt-null"/>').attr('value','all').html('请选择车型').prependTo(models);
  cars.update()
}
function clickResetBtn(){
  resetSelect();
  resetBtn.addClass('current');
  brands.val('all');
}
resetBtn.click(clickResetBtn);


/**
 * 其他选择条件
 */
function selectItem(){
  var $e=jQuery(this);
  $e.siblings('.current').removeClass('current');
  window.selected[$e.data('item')]=$e.data('value');
  cars.update();
  $e.addClass('current');
}
function createItems(items){
  var $e=jQuery(this);
  $e.empty();
  jQuery('<a href="javascript:void(0);" class="current"/>').attr('data-item',$e.attr('id')).attr('data-value','').html('不限').click(selectItem).appendTo($e);
  for(var i=0;i<items.length;i++){
    jQuery('<a href="javascript:void(0);" />').attr('data-item',$e.attr('id')).attr('data-value',items[i].value).html(items[i].name).click(selectItem).appendTo($e);
  }
}
price.update=createItems;
level.update=createItems;
age.update=createItems;
mileage.update=createItems;


/**
 * 选择排序
 */
function selectCondition(){
  var $e=jQuery(this);
  if($e.hasClass('current')){
    var drop=$e.data('drop');
    $e.data('drop', drop=='asc'?'desc':'asc');
    $e.hasClass('drop')?$e.removeClass('drop'):$e.addClass('drop')
  }
  window.selected.condition= $e.data('condition')+' '+$e.data('drop');
  $e.siblings('.current').removeClass('current');
  $e.addClass('current');
  cars.update();
}
condition.update=function (){
  var $e=jQuery(this);
  $e.empty();
  jQuery('<li class="current" />')
    .html('<a href="javascript:void(0);">默认')
    .click(function(){
      window.selected.condition='';
      $(this).siblings('.current').removeClass('current');
      $(this).addClass('current');
      cars.update()
    })
    .appendTo($e);
  jQuery('<li />')
    .html('<a href="javascript:void(0);">价格<i class="img"></a>')
    .data('condition', 'sprice')
    .data('drop', 'asc')
    .click(selectCondition)
    .appendTo($e);
  jQuery('<li />')
    .html('<a href="javascript:void(0);">里程<i class="img"></a>')
    .data('condition', 'mileage')
    .data('drop', 'asc')
    .click(selectCondition)
    .appendTo($e);
};


/**
 * 解析URL中的query字符串 返回json
 */

if (!Function.prototype.bind) { // fix Function bind
  Function.prototype.bind = function(oThis) {
    if (typeof this !== 'function') {
      // closest thing possible to the ECMAScript 5
      // internal IsCallable function
      throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
    }

    var aArgs   = Array.prototype.slice.call(arguments, 1),
      fToBind = this,
      fNOP    = function() {},
      fBound  = function() {
        return fToBind.apply(this instanceof fNOP && oThis
            ? this
            : oThis,
          aArgs.concat(Array.prototype.slice.call(arguments)));
      };

    fNOP.prototype = this.prototype;
    fBound.prototype = new fNOP();

    return fBound;
  };
}

jQuery.extend({
  getQueryParameters : function(str) {
    return (str || document.location.search).replace(/(^\?)/,'').split("&").map(function(n){return n = n.split("="),this[n[0]] = n[1],this}.bind({}))[0];
  }
});
var query2selected = function(){
  jQuery.each(jQuery.getQueryParameters(jQuery(localStorage).attr('search')), function(k, v){
    if(typeof v=='string') v= v.replace(/\+/g,'%20'); //替换 unicode 中 %2B => %20
    if(queryObj[k]) window.selected[k]=decodeURI(v)
  })
};

